
import React, { Component, createRef } from 'react'
import { DownOutlined, PlusOutlined, ExclamationCircleOutlined, MinusOutlined } from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Modal, Switch } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';

import { InfoTypeListByQuery, InfoTypeList, InfoTypeAdd, InfoTypeEdit, InfoTypeDel } from "@/services/infoType";
import arrayToTree from "array-to-tree";
// import moment from "moment"
import UpdateForm from './components/UpdateForm';
import CreateForm from './components/CreateForm';
import {
  FormOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

const actionRef = createRef();

class Info extends Component {
  constructor(props) {
    super(props)
    this.state = {
      options: {},
      SwitchIsEnable: false,
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      expandedRowKeys: [],
      selectedRowKeys: [],
      onSelectFlag: false,
      isExpand: false,
    }
  }

  /**
 * 添加节点
 * @param fields
 */
  async handleAdd(fields) {
    const hide = message.loading('正在添加');
    try {
      const res = await InfoTypeAdd({ ...fields });
      hide();
      if (!res.success) {
        message.error(`添加失败，${res.result}`);
        return false;
      }
      message.success('添加成功');
      // this.reload();
      return true;
    } catch (error) {
      hide();
      message.error(`添加异常，${error}`);
      return false;
    }
  };
  /**
* 更新节点
* @param fields
*/
  async handleUpdate(fields) {
    const hide = message.loading('正在更新');
    try {
      const res = await InfoTypeEdit({
        ...fields,
      });
      hide();
      if (!res.success) {
        message.error(`更新失败，${res.result}`);
        return false;
      }
      message.success('更新成功');
      // this.reload();
      return true;
    } catch (error) {
      hide();
      message.error(`更新异常，${error}`);
      return false;
    }
  };
  /**
 *  删除节点
 * @param selectedRows
 */
  async handleRemove(idList) {
    const hide = message.loading('正在删除');
    try {
      const res = await InfoTypeDel(idList);
      hide();
      if (!res.success) {
        message.error(`删除失败，${res.result}`);
        return false;
      }
      message.success('删除成功');
      // this.reload();
      return true;
    } catch (error) {
      hide();
      message.error(`删除异常，${error}`);
      return false;
    }
  };

  async handleDeal({ fields, serviceMethod, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(`${type}失败，${res.result}`);
        return false;
      }
      message.success(`${type}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }
  async getDataSource(params) {

    const { result, success } = await InfoTypeListByQuery();

    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    //加载选择框
    const tempArr = result.arr.filter(item => item.fid == 0);
    const options = {};
    options[0] = {
      text: "根目录"
    }
    tempArr.forEach(item => {
      options[item.id] = {
        text: item.displayName
      }
    })
    this.setState({
      options
    })

    const data = arrayToTree(result.arr, { rootID: "0", parentProperty: "fid", customID: "id", childrenProperty: "children" })
    return {
      data,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '栏目名',
        dataIndex: 'displayName',
        rules: [{
          required: true,
        }],
      },
      {
        title: '所属栏目',
        dataIndex: 'fdName',
        renderText: text => text ? text : "根目录",
        hideInForm: true,
      },
      {
        title: '显示顺序',
        dataIndex: 'orderNum',
        formItemProps: {
          type: "number"
        },
        rules: [{
          required: true,
        }],
      },
      {
        title: '所属栏目',
        dataIndex: 'fid',
        hideInTable: true,
        valueEnum: this.state.options,
        formItemProps: {
          placeholder: "请选择栏目"
        },
        rules: [{
          required: true,
        }],
      },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Success',
          },
        },
      },
      {
        title: '模版',
        dataIndex: 'type',
        valueEnum: {
          1: {
            text: '简约型',
          },
          2: {
            text: '图文型',
          },
          3: {
            text: '综合型',
          },
          4: {
            text: '图片卡片',
          },
          6: {
            text: '图片卡片1',
          },
          5: {
            text: '文字卡片',
          },
          7: {
            text: '生活服务',
          },
        },
      },
      {
        title: '打开链接',
        dataIndex: 'href',
        hideInTable: true,
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                const selectRow = {
                  ...row,
                  fid: row.fid.toString(),
                  orderNum: row.orderNum.toString(),
                  type: row.type.toString(),
                  isEnable: row.isEnable.toString(),
                }
                this.setState({
                  updateModalVisible: true,
                  selectRow,
                })
              }}
              size="small" type="primary" icon={<FormOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                if (row.children) {
                  message.warn(`请先删除子节点`);
                  return;
                }
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: InfoTypeDel,
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Space>
        ),
      },
    ];
  }

  render() {

    // const rowSelection = {
    //   onSelect: (record, selected, selectedRows) => {
    //     if (record.children) {
    //       if (selected) {
    //         //选择父节点
    //         this.setState({
    //           onSelectFlag: true,
    //           expandedRowKeys: [...new Set([...this.state.expandedRowKeys, record.id])],
    //           selectedRowKeys: [...new Set([...this.state.selectedRowKeys, record.id, ...record.children.map(item => item.id)])],
    //         })
    //       }
    //       else {
    //         const temp = [record.id, ...record.children.map(item => item.id)];
    //         //反选父节点
    //         this.setState({
    //           onSelectFlag: true,
    //           expandedRowKeys: [...new Set([...this.state.expandedRowKeys, record.id])],
    //           selectedRowKeys: this.state.selectedRowKeys.filter(item => !temp.some(sitem => sitem == item)),
    //         })
    //       }
    //     }
    //     else {
    //       if (selected) {
    //         this.setState({
    //           selectedRowKeys: [...new Set([...this.state.selectedRowKeys, record.id])],
    //         })
    //       }
    //       else {
    //         this.setState({
    //           selectedRowKeys: this.state.selectedRowKeys.filter(item => item != record.id),
    //         })
    //       }
    //     }
    //   },
    //   onSelectAll: (selected, selectedRows, changeRows) => {
    //     if (selected) {
    //       this.setState({
    //         selectedRowKeys: selectedRows.map(item => item.id),
    //         expandedRowKeys: selectedRows.map(item => item.id),
    //       })
    //     }
    //     else {
    //       this.setState({
    //         selectedRowKeys: [],
    //         expandedRowKeys: [],
    //       })
    //     }
    //   },
    //   selectedRowKeys: this.state.selectedRowKeys
    // };
    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle={
              <Switch checked={this.state.isExpand}
                onChange={isChecked => {
                  let rootIdList = [];
                  if (isChecked) {
                    rootIdList = Object.keys(this.state.options).map(item => Number(item));
                  }
                  this.setState({
                    isExpand: isChecked,
                    expandedRowKeys: rootIdList,
                  })
                }}
                unCheckedChildren="全部收起" checkedChildren="全部展开" />
              // <Button
              //   onClick={() => {
              //     const isExpand = this.state.isExpand;
              //     let rootIdList = [];
              //     if (!isExpand) {
              //       rootIdList = Object.keys(this.state.options).map(item => Number(item));
              //     }
              //     this.setState({
              //       isExpand: !isExpand,
              //       expandedRowKeys: rootIdList,
              //     })
              //   }}
              // >{this.state.isExpand ? <><MinusOutlined />收起全部</> : <><PlusOutlined />展开全部</>} </Button>
            }
            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            // rowSelection={rowSelection}
            expandable={{
              expandRowByClick: true,
              expandedRowKeys: this.state.expandedRowKeys,
              onExpand: (expanded, record) => {
                if (expanded) {
                  this.setState({
                    expandedRowKeys: [...new Set([...this.state.expandedRowKeys, record.id])],
                  })
                } else {
                  this.setState({
                    expandedRowKeys: this.state.expandedRowKeys.filter(item => item != record.id)
                  })
                }
              }
            }}
            search={false}
            pagination={false}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => {

              return ([
                <Button type="primary" onClick={() => {
                  const selectRow = {
                    orderNum: "0",
                    type: "1",
                    isEnable: "true",
                  }
                  this.setState({
                    createModalVisible: true,
                    selectRow,
                  })
                }}>
                  <PlusOutlined /> 新建
                          </Button>,
                selectedRowKeys && selectedRowKeys.length > 0 && (
                  <Dropdown
                    overlay={
                      <Menu
                        onClick={async e => {
                          if (e.key === 'remove') {
                            // const idList = {
                            //   "id": selectedRowKeys
                            // };
                            // Modal.confirm({
                            //   title: '是否确认删除?',
                            //   icon: <ExclamationCircleOutlined />,
                            //   onOk: async () => {
                            //     const success = await this.handleRemove(idList);
                            //     if (!success) {
                            //       return;
                            //     }
                            //     if (!actionRef.current) {
                            //       return;
                            //     }
                            //     actionRef.current.reload();
                            //   },
                            // });
                          }
                        }}
                        selectedKeys={[]}
                      >
                        <Menu.Item key="remove">批量删除</Menu.Item>
                        <Menu.Item key="approval">批量审批</Menu.Item>
                      </Menu>
                    }
                  >
                    <Button>
                      批量操作 <DownOutlined />
                    </Button>
                  </Dropdown>
                ),
              ]);
            }}
          />
        </MotionLayout>
        <CreateForm
          onCancel={() => this.setState({ createModalVisible: false })}
          createModalVisible={this.state.createModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                infoTypeName: fieldsValues.displayName,
                fid: Number(fieldsValues.fid),
                type: Number(fieldsValues.type),
                orderNum: Number(fieldsValues.orderNum),
                isEnable: fieldsValues.isEnable == "true",
                treeIds: fieldsValues.fid == "0" ? `[]` : JSON.stringify([fieldsValues.fid]),
                rank: fieldsValues.fid == "0" ? 1 : 2,
              }

              const success = await this.handleDeal({
                type: "添加",
                fields,
                serviceMethod: InfoTypeAdd,
              });
              if (!success) {
                return;
              }
              this.setState({
                createModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();

            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
            rowSelection={{}}
          />
        </CreateForm>
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false })}
          updateModalVisible={this.state.updateModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                infoTypeName: fieldsValues.displayName,
                fid: Number(fieldsValues.fid),
                type: Number(fieldsValues.type),
                orderNum: Number(fieldsValues.orderNum),
                isEnable: fieldsValues.isEnable == "true",
                treeIds: fieldsValues.fid == "0" ? `[]` : JSON.stringify([fieldsValues.fid]),
                rank: fieldsValues.fid == "0" ? 1 : 2,
                id: this.state.selectRow.id,
              }
              if (fields.fid == fields.id) {
                message.warn(`所属栏目不能属于自己`);
                return;
              }
              const success = await this.handleDeal({
                type: "更新",
                fields,
                serviceMethod: InfoTypeEdit,
              });
              if (!success) {
                return;
              }
              this.setState({
                updateModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
            rowSelection={{}}
          />
        </UpdateForm>
      </PageHeaderWrapper>
    )
  }
}
export default Info
